<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebRTC to DASH Live Streaming</title>
  <style>
    video {
      /*width: 100%;
      height: auto;*/
      width: 50%;
      height: 30%;
    }
  </style>
</head>
<body>
<h1>WebRTC to DASH Live Streaming Demo</h1>
<button id="startButton">Start Streaming</button>
<div style="float: left;">
  <video id="localVideo" autoplay></video>
</div>
<div style="float: left;">
  <video id="remoteVideo" controls></video>
</div>
<script src="../js/http_cdn.dashjs.org_latest_dash.all.min.js"></script>
<script src="../js/http_cdn.socket.io_4.0.0_socket.io.js"></script>
<!--<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script src="https://cdn.dashjs.org/latest/dash.all.min.js"></script>-->
<script>
  const localVideo = document.getElementById('localVideo');
  const remoteVideo = document.getElementById('remoteVideo');
  const startButton = document.getElementById('startButton');

  let localStream;
  let socket;

  async function startStream() {
    try {
      // 获取摄像头视频流
      localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
      localVideo.srcObject = localStream;

      // 连接到 WebSocket 服务器
      socket = io('http://localhost:8081');

      // 发送视频流到服务器
      socket.on('connect', () => {
        console.log('Connected to WebSocket server');
        socket.emit('startStream', { stream: localStream });

        // 设置远程视频播放器
        const url = 'http://124.70.49.99:8080/dash/stream.mpd';
        const player = dashjs.MediaPlayer().create();
        player.initialize(remoteVideo, url, true);
      });

      // 监听来自服务器的消息
      socket.on('message', (data) => {
        console.log('Received message from server:', data);
      });

      // 监听连接关闭
      socket.on('disconnect', () => {
        console.log('Disconnected from WebSocket server');
      });
    } catch (err) {
      console.error('Error accessing media devices.', err);
    }
  }

  startButton.addEventListener('click', startStream);
</script>
</body>
</html>